import { Component, OnInit, SimpleChanges, Input } from '@angular/core';
import { GanttService } from '../../../services/gantt-chart/gantt.service';
// import { ProgressService } from '../../../services/progress/progress.service';
import { GanttApi } from '../../../services/gantt-chart/gantt.api';
import { ModelService } from '../../../services/model/model.service';
import { NzNotificationService, NzModalService, NzMessageService } from 'ng-zorro-antd';
import * as moment from 'moment';
// import { AclService, AclName, AclPoint } from '../../../core/acl/acl.service';
// import { GanttPermission } from '../../../services/gantt-chart/gantt.permission';
// import { MenuService } from '../../../services/menu/menu.service';
// import { BuildLogService } from '../../../services/project/build-logs/build-log.service';
declare var Neon: any;
@Component({
  selector: 'app-tool-bar',
  templateUrl: './tool-bar.component.html',
  styleUrls: ['./tool-bar.component.scss']
})


export class ToolBarComponent implements OnInit {
  public ganttChecked = false;
  public selector: any;
  public _percent = 0;
  public interval: any;
  public simulate = false;
  public playdisabled = false;
  public pausedisabled = true;
  public startDate = null;
  public showStart = null;
  public endDate = null;
  public finishDate = null;
  public diffDate = null;
  public simulateVisible = false;
  public calenderVisible = false;

  public perStep: any;

  public currentStep = 0;
  public uuids: any = [];

  public playTasks: any = [];
  public permission: any;

  public constructor(
    public ganttService: GanttService,
    private ganttApi: GanttApi,
    private modelService: ModelService,
    // private aclService: AclService,
    private _notification: NzNotificationService,
    // private ganttPermission: GanttPermission,
    // private menuService: MenuService,
    private confirmServ: NzModalService,
    // private buildLogService: BuildLogService,
    private message: NzMessageService
  ) {

  }

  public createNotification = (type, title, message) => {
    this._notification.create(type, title, message);
  }
  public ngOnInit() {
    this.selector = Neon.getSelector();
  }

  public transformDate(value: any) {
    if (typeof value == 'number') {
      return moment.unix(value);
    } else {
      return value;
    }
  }

  // 日历设置
  public calenderShow() {
    this.calenderVisible = true;
  }
  public calenderCancel() {
    this.calenderVisible = false;
  }
  public changeStartDate(group: { name: string, startDate: any, endDate: any }) {
    let startDate = moment(group.startDate);
    let endDate = moment(group.endDate);
    if (!group.endDate) {
      group.endDate = startDate;
      return;
    } else {
      if (startDate.isAfter(endDate)) {
        group.endDate = startDate;
        return;
      }
    }
  }
  public changeEndDate(group: { name: string, startDate: any, endDate: any }) {
    let startDate = moment(group.startDate);
    let endDate = moment(group.endDate);
    if (!group.startDate) {
      group.startDate = endDate;
      return;
    } else {
      if (endDate.isBefore(startDate)) {
        group.startDate = endDate;
        return;
      }
    }
  }
  // deletDate(index: number) {
  //   this.ganttService.ganttProject.exceptDate.splice(index, 1)
  // }
  // addDate() {
  //   this.ganttService.ganttProject.exceptDate.push(
  //     { name: '', startDate: null, endDate: null }
  //   )
  // }
  // calenderOk() {
  //   console.log(this.ganttService.ganttProject.updateCalendar())
  //   let param = this.ganttService.ganttProject;
  //   let that = this;
  //   this.confirmServ.confirm({
  //     nzTitle  : '确认修改例外日期？',
  //     nzContent: '提交将会保存所有任务并重新加载',
  //     nzOnOk() {
  //       that.ganttService.updateGanttInfo(param.updateCalendar()).then(res => {
  //         if (res) {
  //           that.message.success('修改成功')
  //           // that.ganttService.dealWithExceptDate();
  //           // that.ganttService.updateAllTaskInfo()
  //           that.ganttService.saveTasksHanle('保存');
  //           that.calenderVisible = false;
  //         } else {
  //           that.message.error('失败')
  //         }
  //       })
  //     },
  //     nzOnCancel() {
  //     }
  //   });



  // }
  // 保存allTasks
  public saveTasks(type: string) {
    console.log(type);
    this.ganttService.saveTasksHanle(type);
  }

  // 跟踪横道图
  public ganttTracking(e) {
    let ganttChecked = this.ganttChecked;
    this.ganttService.showKeyLine = ganttChecked;
  }

  // 插入新的task
  public addTask() {
    this.ganttService.addTaskHandle('addNewTask');
  }

  // 删除选中元素
  public deleteTask() {
    this.ganttService.showConfirm();
    // this.ganttService.deleteTaskHandle()
  }

  // 降级
  public depressTaskLevel() {
    this.ganttService.depressTaskLevel();
  }

  // //升级
  public promoteTaskLevel() {
    this.ganttService.promoteTaskLevel();
  }

  // 新建gantt
  // newGantt(){
  //   let allTasks = this.ganttService.allTasks;
  //   if(allTasks.length === 0){
  //     this._notification.create('error', '请注意', '进度内容不能为空');
  //   }else{
  //     let that = this;
  //     this.confirmServ.confirm({
  //       nzTitle: '保存当前进度并新建下一级进度？',
  //       // content: '点确认 1 秒后关闭',
  //       nzOnOk() {
  //         that.ganttService.saveTasksHanle('save');
  //         setTimeout(() => {
  //           let step = parseInt(that.ganttService.ganttStep) + 1;
  //           that.menuService.ganttStep = step;
  //           that.menuService.newNextGantt = true;
  //           that.menuService.newProgressModal = true;
  //         }, 500);
  //       },
  //       nzOnCancel() {
  //         return;
  //       }
  //     });

  //   }
  // }

  // 绑定构件
  public bingdingGUID() {
    this.ganttService.bingdingGUID(true);
  }

  // // 解绑构件
  public unbingdingGUID() {
    this.ganttService.unbingdingGUID();
  }


  public addBingdingGUID() {
    this.ganttApi.addFragment();
    // this.modelService.selectFloorShow()
  }

  public configBingdingGUID() {
    this.ganttService.bingdingGUID(false);
  }

  // 关闭进度面板
  public closeGanttPanel() {
    this.modelService.showGanttPanel = false;
  }
  // 新增里程碑
  public addMilepost() {
    this.ganttService.addTaskHandle('milepost');
  }

  // 添加到工作安排
  public addToPlanning() {
    this.ganttService.changePlanning();
  }


  // 退出模拟
  public simulateHide() {
    this.simulate = false;
    // this.modelService.selectFloorShow()
  }

  public refresh() {
    this.ganttService.updateAllTaskInfo();
  }

  public compress() {
    let baseWidth = this.ganttService.baseWidth;
    if (baseWidth > 5) {
      this.ganttService.baseWidth = baseWidth - 5;
      this.ganttService.updateCanvasInfo();
    } else {
      this.message.error('不能再缩小了');
    }
  }

  public expand() {
    let baseWidth = this.ganttService.baseWidth;
    if (baseWidth < 30) {
      this.ganttService.baseWidth = baseWidth + 5;
      this.ganttService.updateCanvasInfo();
    } else {
      this.message.error('不能再放大了');
    }
  }

  public reload() {
    this._percent = 0;
    this.currentStep = 0;
    this.ganttApi.resetState();
    this.playTasks = [];
    this.playdisabled = false;
    this.pausedisabled = true;
  }

  public increase() {
    if (this.interval) {
      clearInterval(this.interval);
    }
    console.log(this.playTasks);
    if (this.currentStep < this.playTasks.length) {
      this._percent = this._percent + this.perStep;
      this.currentStep++;
      this.render();
    } else {
      this._percent = 100;
    }
    this.playdisabled = false;
    this.pausedisabled = true;
  }

  public decline() {
    if (this.interval) {
      clearInterval(this.interval);
    }
    if (this.currentStep > 0) {
      this.remove();
      this._percent = this._percent - this.perStep;
      this.currentStep--;
    } else {
      this.currentStep = 0;
      this._percent = 0;
    }
    this.playdisabled = true;
    this.pausedisabled = false;
  }

  public play() {
    this.playdisabled = true;
    this.pausedisabled = false;
    // let isPlanning = this.ganttPermission.isPlanning;
    this.interval = setInterval(() => {
      if (this.currentStep < this.playTasks.length) {
        this._percent = this._percent + this.perStep;
        this.currentStep++;
        this.render();
      } else {
        this._percent = 100;
        this.currentStep = this.playTasks.length;
        clearInterval(this.interval);
        return;
      }
    }, 1000);
  }


  public pause() {
    if (this.interval) {
      clearInterval(this.interval);
      this.pausedisabled = true;
      this.playdisabled = false;
    }
  }

  public remove() {
    let currentStep = this.currentStep;
    let isPlanning = false;
    if (isPlanning) {
      let uuidItem = this.playTasks[currentStep - 1];
      let uuid = uuidItem.uuid;
      let finishAt = uuidItem.finishAt;
      this.ganttApi.hiddenUuid(uuid);
      // 该构件完成时间
      this.finishDate = moment.unix(finishAt).format('YYYY-MM-DD');
      // 构件时差
      this.diffDate = moment.unix(finishAt).diff(moment(this.startDate), 'days');
    } else {
      let task = this.playTasks[currentStep - 1];
      let symbol = task.symbol;
      let endDate = task.endDate;
      this.ganttApi.hiddenTask(symbol);
      // 该构件完成时间
      this.finishDate = moment(endDate).format('YYYY-MM-DD');
      // 构件时差
      this.diffDate = moment(endDate).diff(moment(this.startDate), 'days');
    }
  }

  public render() {
    let currentStep = this.currentStep;
    let isPlanning = false;
    if (isPlanning) {
      let uuidItem = this.playTasks[currentStep - 1];
      let uuid = uuidItem.uuid;
      let finishAt = uuidItem.finishAt;
      this.ganttApi.renderUuid(uuid);
      // 该构件完成时间
      this.finishDate = moment.unix(finishAt).format('YYYY-MM-DD');
      // 构件时差
      this.diffDate = moment.unix(finishAt).diff(moment(this.startDate), 'days');
    } else {
      let task = this.playTasks[currentStep - 1];
      let symbol = task.symbol;
      let endDate = task.endDate;
      this.ganttApi.renderUuidsFromTask(symbol);
      // 该构件完成时间
      this.finishDate = moment(endDate).format('YYYY-MM-DD');
      // 构件时差
      this.diffDate = moment(endDate).diff(moment(this.startDate), 'days');
    }
  }

  /*
  * 完成时间不能大于开始时间的
  * 禁用开始时间前的日期
   */
  public startValueChange = () => {
    if (this.startDate > this.endDate) {
      this.endDate = null;
    }
  }
  public endValueChange = () => {
    if (this.startDate > this.endDate) {
      this.startDate = null;
    }
  }

  public disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    return endValue.getTime() <= this.startDate.getTime();
  }

  public showModal = () => {
    this.simulateVisible = true;
  }

  public simulateOk = () => {
    console.log('点击了确定');
    this.reload();
    this.getAllplayTasks();
    this.ganttService.detailView = false;
    this.showStart = moment(this.startDate).format('YYYY-MM-DD');
  }

  public simulateCancel = (e) => {
    this.simulateVisible = false;
  }


  public getAllplayTasks() {
    let allTasks = this.ganttService.allTasks;
    let isPlanning = false;
    let playTasks = [];
    let startUnix = moment(this.startDate).hours(0).minutes(0).seconds(0).unix();
    let endUnix = moment(this.endDate).hours(11).minutes(59).seconds(59).unix();
    if (isPlanning) {
      for (let i = 0; i < allTasks.length; i++) {
        const element = allTasks[i];
        let bindings = allTasks[i].bindings;
        if (bindings && bindings.length > 0) {
          bindings.forEach((item) => {
            let finishAt = item.finishAt;
            let uuid = item.uuid;
            if (playTasks.indexOf(item) == -1 && finishAt && finishAt >= moment(this.startDate).unix() && finishAt <= moment(this.endDate).unix()) {
              playTasks.push(item);
            }
          });
        }
      }
      if (playTasks.length > 0) {
        this.playTasks = playTasks;
        this.simulateVisible = false;
        this.perStep = Number((100 / playTasks.length).toFixed(2));
        // 显示进度条
        this.simulate = true;
      } else {
        this.createNotification('error', '请检查', '所选时间段没有绑定的构件');
        return;
      }
    } else {
      // 拼装playTasks
      let playTasks = [];
      let minStart = startUnix;
      for (let i = 0; i < allTasks.length; i++) {
        const element = allTasks[i];
        let task_Start = element.startDate ? moment(element.startDate).unix() : 0;
        let task_End = element.startDate ? moment(element.endDate).unix() : 0;
        if (
          task_Start && task_End &&
          task_Start >= startUnix &&
          task_End <= endUnix &&
          element.bindings && element.bindings.length > 0
        ) {
          playTasks.push(element);
        }
      }

      // playTasks按计划开始时间排序
      for (let i = 0; i < playTasks.length; i++) {
        for (let j = i + 1; j < playTasks.length; j++) {
          if (moment(playTasks[i].startDate).unix() > moment(playTasks[j].startDate).unix()) {
            let tmp = playTasks[i];
            playTasks[i] = playTasks[j];
            playTasks[j] = tmp;
          }
        }
      }

      if (playTasks.length > 0) {
        this.playTasks = playTasks;
        this.simulateVisible = false;
        this.perStep = Math.ceil(100 / this.playTasks.length);
        // 显示进度条
        this.simulate = true;
      } else {
        this.createNotification('error', '请检查', '所选时间段没有绑定的构件');
        return;
      }


    }

    // this.uuids = uuids;
  }



}
